package com.cogent.business.helper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import com.cogent.common.util.ConstantUtil;
import com.cogent.common.util.MapUtil;
import com.cogent.dao.BussinessInstance;
import com.cogent.dao.BussinessQueryHelper;

import com.cogent.dao.domain.QueryParamDomain;
import com.cogent.dao.facade.BussinessDaoFacade;
import com.cogent.dao.type.DistrictControl;
import com.opensymphony.oscache.util.StringUtil;

public class QuerySelectHelper {	
	public static String genSelectField(String cursql, String name, HashMap formMap, boolean isrequred) {
		return genSelectField(cursql, name, formMap, "", "", "", isrequred);
	}
	
	public static String genSelectField(String cursql, String name, HashMap formMap, String defaultvalue,
			String showControl, String classname, boolean isrequred) {
		return genSelectField(cursql, name, formMap, defaultvalue, showControl, classname, isrequred, false);
	}
	
	public static String genSelectField(String cursql, String name, HashMap formMap, String defaultvalue,
			String showControl, String classname, boolean isrequred, boolean isdisabled) {
		String[] typecodes = cursql.split("\\|");
		String sql = typecodes[0];
		String orderby = "";
		if(typecodes.length > 1)
			orderby = typecodes[1];
		List queryList = new ArrayList();
		HashMap curQueryMap = new HashMap();
		if(typecodes.length > 2) {
			if(!StringUtil.isEmpty(typecodes[2])) {
				String[] param = typecodes[2].split(";");
				for(int i=0; i<param.length; i++) {
					String[] curtemps = param[i].split("~");
					String value = MapUtil.getStringValue(formMap, curtemps[0]);
					if(curtemps[0].equals("districtcode"))
						queryList.add(new QueryParamDomain(curtemps[1], curtemps[0], DistrictControl.getControlCode(value), DistrictControl.getQueryType(value)));
					else
						queryList.add(new QueryParamDomain(curtemps[1], curtemps[0], value));
					curQueryMap.put(curtemps[0], value);
				}
			}
		}
		String curName = name;
		if(curName.indexOf(".") > 0)
			curName = curName.substring(curName.indexOf(".")+1);
		String curdefaultValue = MapUtil.getStringValue(formMap, curName);
		if(typecodes.length > 3) {
			String[] curtemp = typecodes[3].split("~");
			curdefaultValue = "";
			for(int i=0; i<curtemp.length; i++)
				curdefaultValue += MapUtil.getStringValue(formMap, curtemp[i]) + "~";
			if(curdefaultValue.length() > 0)
				curdefaultValue = curdefaultValue.substring(0, curdefaultValue.length()-1);
		}
		 
			List list = BussinessQueryHelper.query(sql, queryList, orderby);
			 
		StringBuffer str = new StringBuffer();
		str.append("<select name=\"").append(name).append("\" id=\"").append(name).append("\"")
			.append(showControl).append(classname).append("/>");
		int level = 1;
		String defname = "";
		if(!StringUtil.isEmpty(defaultvalue)) {
			String[] temp = defaultvalue.split("\\|");
			if(temp.length > 1)
				defname = temp[1];
		}
		int keyindex = getKeyIndex(typecodes, defname);
		String seldefname = "--请选择";
		String seldefvale = "";
		String selValue = name;
		String defvalue = "";
		if(isdisabled) {
			Iterator it = list.iterator();
			while(it.hasNext()) {
				HashMap dataMap = (HashMap)it.next();
				defvalue = getDeafultValue(keyindex, defaultvalue, dataMap);
				if(!StringUtil.isEmpty(defvalue)) {
					seldefvale = defvalue;
					seldefname = MapUtil.getStringValue(dataMap, "enumoption");
					selValue = defvalue;
					break;
				}
			}
		}
		str.append(HtmlUIHelper.getOption(seldefname, seldefvale, selValue, level));
		if(list.size() > 0) {
			HashMap curMap = (HashMap)list.get(0);
			level = MapUtil.getIntValue(curMap, "enumlevel", 1) - 1;
		}
		
		Iterator it = list.iterator();
		while(it.hasNext()) {
			HashMap dataMap = (HashMap)it.next();
			if(MapUtil.getStringValue(dataMap, "enumvalue").equals(seldefvale))
				continue;
			str.append(HtmlUIHelper.getOption(MapUtil.getStringValue(dataMap, "enumoption"),
						MapUtil.getStringValue(dataMap, "enumvalue"), curdefaultValue,
						MapUtil.getIntValue(dataMap, "enumlevel") - level));
		}
		str.append("</select>");
		if(isrequred)
			str.append("<span class=\"txt_red\">&nbsp;*</span>");
		return str.toString();
	}
	
	private static String getDeafultValue(int keyindex, String defaultvalue, HashMap dataMap) {
		String ret = "";
		if(!StringUtil.isEmpty(defaultvalue)) {
			String[] temp = defaultvalue.split("\\|");
			if(temp.length == 1)
				ret = temp[0];
			else {
				String curenumvalue = MapUtil.getStringValue(dataMap, "enumvalue");
				String[] enumvalue = curenumvalue.split("~");
				if((keyindex == -1) && (curenumvalue.equals(defaultvalue)))
					ret = MapUtil.getStringValue(dataMap, "enumvalue");
				else if((keyindex != -1) && (enumvalue[keyindex].equals(temp[0])))
					ret = MapUtil.getStringValue(dataMap, "enumvalue");
			}
		}
		
		return ret;
	}
	
	private static int getKeyIndex(String typecodes[], String name) {
		if(name.indexOf("~") > 0)
			return -1;
		int keyindex = 0;
		if(typecodes.length > 3) {
			String[] curtemp = typecodes[3].split("~");
			for(int i=0; i<curtemp.length; i++) {
				if(curtemp[i].equals(name))
					keyindex = i;
			}
		}
		
		return keyindex;
	}
	
	public static String getShowValue(String cursql, String name, HashMap formMap) {
		String[] typecodes = cursql.split("\\|");
		String sql = typecodes[0];
		String orderby = "";
		if(typecodes.length > 1)
			orderby = typecodes[1];
		List queryList = new ArrayList();
		HashMap curQueryMap = new HashMap();
		if(typecodes.length > 2) {
			if(!StringUtil.isEmpty(typecodes[2])) {
				String[] param = typecodes[2].split(";");
				for(int i=0; i<param.length; i++) {
					String[] curtemps = param[i].split("~");
					String value = MapUtil.getStringValue(formMap, curtemps[0]);
					if(curtemps[0].equals("districtcode"))
						queryList.add(new QueryParamDomain(curtemps[1], curtemps[0], DistrictControl.getControlCode(value), DistrictControl.getQueryType(value)));
					else
						queryList.add(new QueryParamDomain(curtemps[1], curtemps[0], value));
					curQueryMap.put(curtemps[0], value);
				}
			}
		}
		String defaultValue = MapUtil.getStringValue(formMap, name);
		if(typecodes.length > 3) {
			String[] curtemp = typecodes[3].split("~");
			defaultValue = "";
			for(int i=0; i<curtemp.length; i++)
				defaultValue += MapUtil.getStringValue(formMap, curtemp[i]) + "~";
			if(defaultValue.length() > 0)
				defaultValue = defaultValue.substring(0, defaultValue.length()-1);
		}
		int keyindex = getKeyIndex(typecodes, name);
	 
		List list = BussinessQueryHelper.query(sql, queryList, orderby);
			 
		String ret = "";
		Iterator it = list.iterator();
		while(it.hasNext()) {
			HashMap dataMap = (HashMap)it.next();
			String curenumvalue = MapUtil.getStringValue(dataMap, "enumvalue");
			String[] enumvalue = curenumvalue.split("~");
			if((keyindex == -1) && (curenumvalue.equals(defaultValue))){
				ret = MapUtil.getStringValue(dataMap, "enumoption");
				break;
			}else if((keyindex != -1) && (enumvalue[keyindex].equals(defaultValue))) {
				ret = MapUtil.getStringValue(dataMap, "enumoption");
				break;
			}
		}
		
		return ret;
	}
	
	public static String getMutilSelect(String sql, String name, HashMap formMap) {
		StringBuffer str = new StringBuffer();
		 
			List list = BussinessQueryHelper.query(sql, new ArrayList(), "");
		 
		 
		HashMap selMap = new HashMap();
		if(!MapUtil.isEmpty(formMap, name)) {
			String[] temps = MapUtil.getStringValue(formMap, name).split(",");
			for(int i=0; i<temps.length; i++)
				selMap.put(temps[i], new HashMap());
		}
		str.append("<td class='td_data'>").append("<select id=\"bychoiced\" multiple size=\"10\" ondblclick=\"additem('bychoiced', 'selchoiced')\">");
		Iterator it = list.iterator();
		while(it.hasNext()) {
			HashMap curMap = (HashMap)it.next();
			String enumvalue = MapUtil.getStringValue(curMap, "enumvalue");
			if(selMap.containsKey(enumvalue))
				selMap.put(enumvalue, curMap);
			else {
				str.append("<option value=\"").append(enumvalue).append("\">")
					.append(MapUtil.getStringValue(curMap, "enumoption")).append("</option>");
			}
		}
		str.append("</select></td>")
			.append("<td class='td_data'>").append("<a href=\"javascript:;\" onclick=\"additem('bychoiced', 'selchoiced')\">").append("<input type=\"button\" value=\"选择\"/></a>")
			.append("<br/>").append("<a href=\"javascript:;\" onclick=\"delitem('bychoiced', 'selchoiced')\">").append("<input type=\"button\" value=\"取消\"/></a></td>")
			.append("<td class='td_data'><select id=\"selchoiced\" multiple size=\"10\" ondblclick=\"delitem('bychoiced', 'selchoiced')\">");
		it = selMap.keySet().iterator();
		while(it.hasNext()) {
			String key = it.next().toString();
			HashMap curMap = (HashMap)selMap.get(key);
			str.append("<option value=\"").append(MapUtil.getStringValue(curMap, "enumvalue")).append("\">")
				.append(MapUtil.getStringValue(curMap, "enumoption")).append("</option>");
		}
		str.append("</select></td>");
		
		return str.toString();
	}
	
	public static String getMutilSelectValue(String sql, String name, HashMap formMap) {
		StringBuffer str = new StringBuffer();
		List list = BussinessQueryHelper.query(sql); 
		HashMap selMap = new HashMap();
		if(!MapUtil.isEmpty(formMap, name)) {
			String[] temps = MapUtil.getStringValue(formMap, name).split(",");
			for(int i=0; i<temps.length; i++)
				selMap.put(temps[i], new HashMap());
		}
		Iterator it = list.iterator();
		while(it.hasNext()) {
			HashMap curMap = (HashMap)it.next();
			String enumvalue = MapUtil.getStringValue(curMap, "enumvalue");
			if(selMap.containsKey(enumvalue))
				selMap.put(enumvalue, curMap);
		}
		it = selMap.keySet().iterator();
		while(it.hasNext()) {
			String key = it.next().toString();
			HashMap curMap = (HashMap)selMap.get(key);
			str.append(MapUtil.getStringValue(curMap, "enumoption")).append(",");
		}
		
		String temp = str.toString();
		if(temp.length() > 0)
			temp = temp.substring(0, temp.length()-1);
		
		return temp;
	}
	
	public static HashMap getChacheValueByID(String sql) {
		String tableName = getTableName(sql).toLowerCase();
		 	HashMap curMap = BussinessQueryHelper.queryOneRow(sql, new ArrayList());
			 
		
		return curMap;
	}
	
	public static void refreshCacheByID(String sql, Object curMap) {
		BussinessQueryHelper.refQueryCache(sql);
	
	}
	
	public static String getTableName(String sql) {
		String temp = sql.toLowerCase();
		if(temp.indexOf(" from ")>0) {
			temp = temp.substring(temp.indexOf(" from ") + 6);
			int start = temp.indexOf(" ");
			if(start == 0)
				temp = temp.substring(1);
			start = temp.indexOf(" ");
			if(start > 0)
				temp = temp.substring(0, start);
		}
		
		return temp;
	}
}
